package com.peking.donations.config;

import com.google.common.collect.Maps;
import com.peking.donations.plugins.pay.wx.constants.CacheNames;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import java.util.Map;

/**
 * Created by WYZ on 16/3/24.
 */
@Configuration
@EnableRedisHttpSession
public class RedisConfiguration {

    @Bean
    public static ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(template.getStringSerializer());
        return template;
    }

    @Bean
    CacheManager cacheManager() {
        Map<String, Long> cacheMap = Maps.newHashMap();
        cacheMap.put(CacheNames.WX_ACCESS_TOKEN.name(),7200l);
        cacheMap.put(CacheNames.WX_JS_API_TICKET.name(),7200l);
        cacheMap.put(CacheNames.PAY_SUCCESS_TRANSACTIONS.name(),0l);
        cacheMap.put(CacheNames.PAY_FAILED_TRANSACTIONS.name(),0l);
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate(), cacheMap.keySet());
        redisCacheManager.setExpires(cacheMap);
        redisCacheManager.setUsePrefix(true);
        return redisCacheManager;
    }


}
